package com.sakiko.rag.config;

import com.sakiko.rag.service.ChatAssistant;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import dev.langchain4j.store.embedding.qdrant.QdrantEmbeddingStore;
import io.qdrant.client.QdrantClient;
import io.qdrant.client.QdrantGrpcClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * projectName: com.sakiko.rag.config
 *
 * @author: sakiko
 * time: 2025/8/30 17:46
 * description: 配置
 */
@Configuration
public class LLMConfig {

    @Bean
    public ChatModel chatModel() {
        return OpenAiChatModel.builder()
                .apiKey(System.getenv("ALIBABA_BAILIAN_API_KEY"))
                .modelName("qwen-plus")
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();
    }

//    // 创建 Qdrant客户端
//    @Bean // 创建库用，可不用
//    public QdrantClient qdrantClient() {
//        QdrantGrpcClient.Builder grpcClientBuilder =
//                QdrantGrpcClient.newBuilder("192.168.6.100", 6334, false);
//
//        return new QdrantClient(grpcClientBuilder.build());
//    }
//
//    @Bean
//    public EmbeddingStore<TextSegment> embeddingStore() {
//        return QdrantEmbeddingStore.builder()
//                .host("192.168.6.100")
//                .port(6334)
//                .collectionName("test-qdrant")
//                .build();
//    }

    // 嵌入存储 (矢量数据库)的其他方式 - 14
    @Bean
    public InMemoryEmbeddingStore<TextSegment> inMemoryEmbeddingStore() {
        return new InMemoryEmbeddingStore<>();
    }

    @Bean
    public ChatAssistant assistant(ChatModel chatModel, EmbeddingStore<TextSegment> embeddingStore) {
        return AiServices.builder(ChatAssistant.class)
                .chatModel(chatModel)
                .chatMemory(MessageWindowChatMemory.withMaxMessages(50)) // 记忆上下文长度
                .contentRetriever(EmbeddingStoreContentRetriever.from(embeddingStore)) // 内容检索
                .build();
    }


}
